package com.summer_administration.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.summer_administration.exception.BusinessException;
import com.summer_administration.mapper.MemberMapper;
import com.summer_administration.pojo.Member;
import com.summer_administration.pojo.PageBean;
import com.summer_administration.service.MemberService;
import com.summer_administration.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Override
    @Transactional
    public void add(Member member) {
        // 验证联系方式唯一性
        if (memberMapper.existsByNumber(member.getNumber())) {
            throw new BusinessException("联系方式已存在");
        }

        // 设置创建信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        member.setCreateUser((Integer) userInfo.get("id"));
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());

        memberMapper.add(member);
    }

    @Override
    public PageBean<Member> list(Integer pageNum, Integer pageSize) {
        PageBean<Member> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        Page<Member> page = (Page<Member>) memberMapper.listByUser(userId);

        //pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());
        return pb;
    }

    @Override
    @Transactional
    public void update(Member member) {
        Member existing = memberMapper.getById(member.getId());
        if (existing == null) {
            throw new BusinessException("成员不存在");
        }

        // 验证联系方式冲突
        if (!existing.getNumber().equals(member.getNumber())
                && memberMapper.existsByNumber(member.getNumber())) {
            throw new BusinessException("联系方式已存在");
        }

        // 保留创建信息
        member.setCreateUser(existing.getCreateUser());
        member.setCreateTime(existing.getCreateTime());
        member.setUpdateTime(LocalDateTime.now());

        memberMapper.update(member);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        if (memberMapper.getById(id) == null) {
            throw new BusinessException("成员不存在");
        }

        // 检查是否关联小组
        /*if (memberMapper.countGroupRelations(id) > 0) {
            throw new BusinessException("成员已关联小组，无法删除");
        }*/

        memberMapper.delete(id);
    }

    @Override
    public List<Member> getDetailsByMemberName(String memberName) {
        return memberMapper.selectByMemberName(memberName);
    }
}
